// 账号登录
<template>
  <div>
    <el-form :model="formData" label-width="70px" ref="ruleForm">
      <el-form-item
        label="账号"
        prop="name"
        :rules="{
          required: true,
          message: '账号不能为空',
          trigger: ['blur', 'change'],
        }"
      >
        <el-input
          placeholder="请输入账号"
          v-model="formData.name"
          maxlength="12"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="密码"
        prop="password"
        :rules="{
          required: true,
          message: '密码不能为空',
          trigger: ['blur', 'change'],
        }"
      >
        <el-input
          placeholder="请输入密码"
          v-model="formData.password"
          show-password
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { defineComponent, reactive, ref } from 'vue'
import { getNmae, setPassword } from '@/utils/localStorage.js'

import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default defineComponent({
  setup () {
    const formData = reactive({
      name: getNmae('name') || '',
      password: getNmae('password') || ''
    })
    const store = useStore() // vuex实例
    const Router = useRouter()
    const ruleForm = ref()
    const loginAction = (keepPassword) => {
      ruleForm.value.validate(async (valid) => {
        if (valid) {
          if (keepPassword) {
            // 利用本地存储 保存密码和账号 点了记住密码
            setPassword('name', formData.name)
            setPassword('password', formData.password)
          }
          await store.dispatch('login/LoginAction', formData) // 调用 vuex中 login模块的方法 异步请求使用 dispatch
          Router.push({
            // 路由跳转
            path: '/'
          })
        } else {
          return false
        }
      })
    }
    return {
      formData,
      loginAction,
      ruleForm,
      store
    }
  }
})
</script>

<style lang="less" scoped>
</style>
